package com.lmmob.autotest.uitest.controls;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.containsString;

public class SuggestBox extends Control implements ValueSettable {
    private String itemId;

    public SuggestBox(String itemId, WebDriver webDriver) {
        super(webDriver);
        this.itemId = itemId;
    }

    @Override
    protected String getSelfQuery() {
        return String.format(".query(\"[itemId='%s']\")[0]", itemId);
    }

    public void suggest(String value) {
        WebElement inputElement = getInputElement();
        inputElement.clear();
        inputElement.sendKeys(value);
        //TO DO fixed it
        waitAWhile(3, TimeUnit.SECONDS);
        String pickerId = getPickerId();
        List<WebElement> searchItems = findElement(By.id(pickerId)).findElements(By.className("search-item"));
        assertThat(String.format("We can not get any suggests for %s", itemId), searchItems.size(), greaterThanOrEqualTo(1));
        searchItems.get(0).click();
    }

    private WebElement getInputElement() {
        String id = (String) runScript("return " + getQuery() + ".id");
        List<WebElement> elements = findElement(By.id(id)).findElements(By.tagName("input"));
        for (WebElement element : elements) {
            if (element != null && element.isDisplayed()) {
                return element;
            }
        }
        return null;
    }

    private String getPickerId() {
        return (String) runScript("return " + this.getQuery() + ".picker.id");
    }

    @Override
    protected String getName() {
        return this.itemId;
    }

    public void setValue(String value) {
        this.suggest(value);
    }

    public void verifyValue(String expected) {
        WebElement inputElement = getInputElement();
        assertThat(String.format("SuggestBox[itemId='%s']", this.itemId), inputElement.getAttribute("value"), containsString(expected));
    }
}
